<template>
<div class="add-product">
  <!--面包屑导航-->
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item :to="{ path: '/goods' }">商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>添加商品</el-breadcrumb-item>
  </el-breadcrumb>
  <!--内容区-->
  <el-card>
    <el-row class="m-b">
      <el-col>
        <el-alert
          title="添加商品信息"
          type="info"
          center
          show-icon
          :closable="false"
        >
        </el-alert>
      </el-col>
    </el-row>
    <!--步骤条区域-->
    <el-row>
      <el-col>
        <el-steps
          :space="200"
          :active="activeIndex - 0"
          align-center
          finish-status="success"
        >
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
      </el-col>
    </el-row>
    <!--纵向tabs区域-->
    <el-row>
      <el-col>
        <el-form :model="addProductruleForm" :rules="addProductrules" ref="addProductruleForm" label-position="top" class="demo-ruleForm">
        <el-tabs :tab-position="tabPosition" v-model="activeIndex" :before-leave="changeTabs" @tab-click="changeTabsClick">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addProductruleForm.goods_name"  name="goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addProductruleForm.goods_price" type="number"  name="goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addProductruleForm.goods_weight" name="goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addProductruleForm.goods_number" name="goods_number"  type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                props.expandTrigger='hover'
                v-model="selectId"
                :options="CateList"
                :props="cascaderProps"
                @change="cateChange"
                :popper-append-to-body="false"
                clearable
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!--遍历循环动态参数-->
            <el-form-item v-for="(item, index) in manyData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox
                v-for="(item2,index) in item.attr_vals"
                :label="item2"
                :key="index"
                border
              >
                {{item2}}
              </el-checkbox>
            </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!--遍历循环静态属性-->
            <el-form-item v-for="(item, index) in onlyData"  :key="item.attr_id" :label="item.attr_name" >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!--图片上传-->
            <el-upload
              :action="uploadApi"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :headers="headerToken"
              :on-success="uploadSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2048kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!--富文本编辑器quill-editor-->
            <quill-editor class="m-b" content-type='html' v-model="addProductruleForm.goods_introduce"
            >
            </quill-editor>
          <!--添加文本按钮-->
            <el-button type="primary" @click="addProduct">添加商品描述</el-button>
          </el-tab-pane>
          <el-tab-pane label="完成" name="5">完成</el-tab-pane>
        </el-tabs>
        </el-form>
      </el-col>
    </el-row>
    <!--图片预览对话框-->
    <el-dialog
      title="图片预览"
      :visible.sync="filePreviewdialogVisible"
      width="30%"
    >
      <div class="img-box-preview">
        <img :src="fileTempPath" alt="点击可以查看大图" @click="showPic(fileTempPath)">
      </div>
    </el-dialog>
  </el-card>
</div>
</template>

<script>
export default {
  name: 'addProduct',
  data(){
    return{
      // 步骤条进度标识
      activeIndex: '0',
      // tabs标签方向
      tabPosition: 'left',
      // 提交的表单数据
      addProductruleForm:{
        // 商品名称
        goods_name:'',
        // 以为','分割的分类列表
        goods_cat:'',
        // 价格
        goods_price: 0,
        // 数量
        goods_number: 0,
        // 重量
        goods_weight: 0,
        // 介绍
        goods_introduce:'',
        // 上传的图片临时路径
        pics:[],
        // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        attrs:[],
      },
      // 商品的分类id
      selectId: '',
      // 商品-级联选择器分类规则
      cascaderProps:{
        // 分类的名称
        label: 'cat_name',
        // 分类的id
        value: 'cat_id',
        // 父子节点嵌套关键字
        children: 'children',
        checkStrictly: true,
        size: 'medium'
      },
      // 分类数据
      CateList: [],
      // 当前分类动态参数数据
      manyData:[],
      // 当前分类静态属性数据
      onlyData:[],
      // 表单的验证规则
      addProductrules: {
        // 验证用户名
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品商量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ]
      },
      // 图片上传接口
      uploadApi:'http://127.0.0.1:8888/api/private/v1/upload/',
      // 上传图片数组
      fileList:[],
      // 上传图片token: Authorization
      headerToken:{
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览对话框显示控制
      filePreviewdialogVisible: false,
      // 图片预览地址
      fileTempPath: ''
    }
  },
  mounted() {
    // this.$refs.radio.$children.forEach((item) => {
    //   item.$refs.radio.removeAttribute("aria-hidden");
    // })
  },
    created() {
    this.getCateList()
  },
  methods:{
    // tabs事件切换前监控
    changeTabs(activeName, oldActiveName){
      if(oldActiveName === '0' && this.selectId.length !== 3) {
        this.$message.error('请先选择三级分类进行商品添加！')
        return false
      }
    },
    // tabs事件点击监控
    async changeTabsClick(){
      console.log('tabs事件点击监控', this.activeIndex)
      console.log('分类id', this.selectId[2])
      if(this.activeIndex === '1'){
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {params:{sel: 'many'}})
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 拆分参数为数组
        res.data.forEach((item)=>{
          item.attr_vals = item.attr_vals?item.attr_vals.split(','):[]
        })
        this.manyData = res.data
      }
      if(this.activeIndex === '2'){
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {params:{sel: 'only'}})
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 拆分属性为数组
        // res.data.forEach((item)=>{
        //   item.attr_vals = item.attr_vals?item.attr_vals.split(','):[]
        // })
        console.log('属性拆分数组',this.onlyData )
        this.onlyData = res.data
      }
    },
    // 获取商品分类数据
    async getCateList() {
      const {data: res} = await this.$http.get(`categories`)
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.CateList = res.data
    },
    // 级联选择器事件
    cateChange(val) {
      // 如果没有选择三级分类 提示并清空已选择分类
      if(val.length !== 3){
        this.selectId = []
        return this.$message.error('请选择三级分类进行商品添加！')
      }
      console.log('级联选择器选择事件', this.selectId)
      this.addProductruleForm.goods_cat = this.selectId.join(',')
    },
    // 图片上传成功处理
    uploadSuccess(response, file, fileList){
      if(response.meta.status !== 200) return this.$message.error('商品图片上传失败！')
      // 拼接图片地址对象，并push进数组
      const picInfo = {
        pic: response.data.tmp_path
      }
      this.addProductruleForm.pics.push(picInfo)
      console.log('图片上传成功', this.addProductruleForm)
      this.$message.success('商品图片上传成功！')
    },
    // 图片删除
    handleRemove(file) {
      console.log(file);

      const filePath = file.response.data.tmp_path
      // 利用箭头函数和findIndex实现遍历
      const j = this.addProductruleForm.pics.findIndex(item=>
        item.pic === filePath
      )
      // 利用for循环遍历变量多，效率低
      // let j = 0
      // for(let i in this.addProductruleForm.pics){
      //   console.log('i is ',i)
      //   if(this.addProductruleForm.pics[i].pic === filePath){
      //     j = i
      //   }
      // }
      this.addProductruleForm.pics.splice(j,1)
      console.log('图片删除成功', this.addProductruleForm)
    },
    // 图片预览
    handlePreview(file) {
      console.log(file);
      this.filePreviewdialogVisible = true
      this.fileTempPath = file.response.data.url
    },
    // 点击在新窗口查看大图
    showPic(url){
      window.open(url, '_blank')
    },
    // 添加商品
    async addProduct(){
      console.log('添加商品事件', this.addProductruleForm)
      // 添加商品参数事件
      this.manyData.forEach((item)=>{
        const itemInfo ={
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(',')
        }
        this.addProductruleForm.attrs.push(itemInfo)
      })
      // 添加商品属性事件
      this.onlyData.forEach((item)=>{
        const itemInfo ={
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        this.addProductruleForm.attrs.push(itemInfo)
      })
      this.$refs.addProductruleForm.validate(async(valid)=>{
        if(!valid){
          return this.$message.error('请检查表单，确认填写完整')
        }
        // 执行添加接口，提交数据
        const {data: res} = await this.$http.post(`goods`, this.addProductruleForm)
        if(res.meta.status !== 201) return this.$message.error('添加商品失败！')
        // 添加商品成功
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    }
  },
  computed:{
    cateId(){
      if(this.selectId.length === 3){
        return this.selectId[2]
      }
      return null
    }
  }
}
</script>

<style lang="scss">
.m-b{
  margin-bottom: 15px;
}
.el-cascader-panel{
  height: 300px !important;
}
::v-deep .el-step__title{
  font-size: 14px !important;
}
.el-checkbox{
  margin:  0 10px 0 0;
}
.el-cascader{
  width: 30%;
}
.img-box-preview>img{
  display: block;
  width: 100%;
  height: auto;
}
::v-deep .ql-editor{
  min-height: 400px;
}
</style>
